# This short notebook will show how to take symbolic derivatives in Python.
# We will require the 'SymPy' module.
import sympy as sym
# First, let's define a symbol x.
x = sym.Symbol('x')
# Then we can define f in terms of x.
f = 2*x**2+3
f
# To evaluate f at a particular value of x, we can use 'subs()'.
z = f.subs(x, 2)
print('2(2)^2 + 3 =', z)
2(2)^2 + 3 = 11
# To take the derivative of f with respect to x, we use 'diff()'.
dfdx = f.diff(x)
dfdx
# Of course, we can now evaluate the derivative at a particular value of x.
print('df/dx at x = 3 is', dfdx.subs(x, 3))
df/dx at x = 3 is 12
# We can make our functions more complicated. Here's a function of two variables.
y = sym.Symbol('y')
g = 2*sym.sin(x)**y**2
g
# Here's how you can use 'subs()' to subsitute values for multiple variables.
z = g.subs({x:1, y:2})
sym.N(z)
# Here's the x-derivative of g...
g.diff(x)
# and here's the y-derivative.
g.diff(y)
# Alternatively, you can define Python functions.
def fcn(x):
return 2*x**2 + 3
# One advantage of this method is that it is easy to now evaluate the value
# of fcn at any x.
z = fcn(2)
print('2(2)^2 + 3 =', z)
2(2)^2 + 3 = 11
# The derivatives of these functions are calculated in the way.
dgdx = fcn(x).diff(x)
print('dg/dx =', dgdx)
dg/dx = 4*x
# Note that there is another way to call the 'diff()' function.
dgdx = sym.diff(fcn(x), x)
print('dg/dx =', dgdx)
dg/dx = 4*x
# Of course, you can have functions of multiple variables.
def gcn(x, y):
return 2*sym.sin(x)**y**2
sym.N(gcn(1, 2))
# You can evaluate the partial derivatives in the way that you'd expect:
gcn(x, y).diff(x), gcn(x, y).diff(y)
(2*y**2*sin(x)**(y**2)*cos(x)/sin(x), 4*y*log(sin(x))*sin(x)**(y**2))